<template>
  <div class="publish-container">
    <el-card class="publish-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h1 class="title">发布商品</h1>
        </div>
      </template>

      <el-form 
        :model="product" 
        :rules="rules" 
        ref="productForm"
        label-position="top"
        @submit.prevent="submitProduct"
      >
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="product.name"
            placeholder="请输入商品名称"
            clearable
            :prefix-icon="Goods"
          />
        </el-form-item>

        <!-- 商品分类 -->
        <el-form-item label="商品分类" prop="category">
          <el-cascader
            v-model="product.category"
            :options="categoryOptions"
            placeholder="请选择商品分类"
            :props="{ expandTrigger: 'hover', checkStrictly: true }"
            clearable
            style="width: 100%"
            @change="handleCategoryChange"
          />
        </el-form-item>

        <!-- 商品图片上传 -->
        <el-form-item label="商品图片 (最多9张)" prop="images">
          <el-upload
            :file-list="product.fileList"
            @change="handleFileChange"
            @remove="handleRemove"
            action="#"
            list-type="picture-card"
            :multiple="true"
            :limit="9"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :auto-upload="false"
            accept="image/*"
            class="image-uploader"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                点击上传图片，支持JPG/PNG格式，单张不超过5MB
              </div>
            </template>
          </el-upload>
          
          <el-dialog v-model="dialogVisible" width="70%">
            <img w-full :src="dialogImageUrl" alt="预览图片" style="max-height: 70vh; object-fit: contain;" />
          </el-dialog>
        </el-form-item>

        <!-- 商品描述 -->
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="product.description"
            type="textarea"
            :rows="4"
            placeholder="请输入商品详细描述"
            maxlength="500"
            show-word-limit
            resize="none"
          />
        </el-form-item>

        <!-- 价格设置 -->
        <el-form-item label="价格设置" prop="price">
          <el-input
            v-model="priceInput"
            placeholder="请输入商品价格"
            clearable
            @input="formatPrice"
          >
            <template #prefix>
              <span style="color: #666">¥</span>
            </template>
            <template #append>
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>

        <!-- 发货地 -->
        <el-form-item label="发货地" prop="delivery_location">
          <el-cascader
            v-model="product.delivery_location"
            :options="locationOptions"
            placeholder="请选择发货地"
            :props="{ expandTrigger: 'hover' }"
            clearable
            style="width: 100%"
          />
        </el-form-item>

        <!-- 发货方式 -->
        <el-form-item label="发货方式" prop="delivery_method">
          <el-select
            v-model="product.delivery_method"
            placeholder="请选择发货方式"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="method in shippingMethods"
              :key="method.value"
              :label="method.label"
              :value="method.value"
            />
          </el-select>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item class="button-group">
          <el-button
            type="primary"
            native-type="submit"
            class="submit-btn"
            :loading="isSubmitting"
          >
            发布商品
          </el-button>
          <el-button
            type="info"
            class="draft-btn"
            :loading="isSubmitting"
            @click="saveAsDraft"
          >
            存为草稿
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, watch } from 'vue'
import { Goods, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import apiClient from '../../utils/request'
// 表单数据
const product = reactive({
  name: '',
  category: [], // 分类 [一级分类, 二级分类]
  fileList: [], // 存储el-upload组件的文件列表
  description: '',
  price: 0,
  delivery_location: [],
  delivery_method: '',
  action: 'publish'
})

// 价格输入框的双向绑定
const priceInput = ref('')

// 商品分类选项 - 初始为空，将从API获取
const categoryOptions = ref([])

// 发货地选项

const locationOptions = ref([
  {
    value: 'A校区',
    label: 'A校区',
    children: [
      { value: '主教学楼', label: '主教学楼' },
      { value: '北苑宿舍区', label: '北苑宿舍区' },
      { value: '南门快递点', label: '南门快递点' }
    ]
  },
  {
    value: 'B校区',
    label: 'B校区',
    children: [
      { value: '图书馆', label: '图书馆' },
      { value: '体育中心', label: '体育中心' },
      { value: '西区食堂', label: '西区食堂' }
    ]
  },
  {
    value: 'C校区',
    label: 'C校区',
    children: [
      { value: '实验楼区', label: '实验楼区' },
      { value: '东花园', label: '东花园' },
      { value: '科技园区', label: '科技园区' }
    ]
  }
])
// 发货方式选项
const shippingMethods = ref([
  { value: 0, label: '包邮' },
  { value: 1, label: '按距离计费' },
  { value: 2, label: '一口价' },
  { value: 3, label: '无需邮寄' }
])

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在2到30个字符', trigger: 'blur' }
  ],
  category: [
    { 
      validator: (rule, value, callback) => {
        if (!value || value.length !== 2) {
          callback(new Error('请选择完整的商品分类'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  fileList: [],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 5, message: '至少输入5个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (isNaN(value) || value <= 0) {
          callback(new Error('价格必须大于0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  delivery_location: [
    { 
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请选择发货地'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  delivery_method: [
    { required: true, message: '请选择发货方式', trigger: 'change' }
  ]
})

const productForm = ref(null)
const isSubmitting = ref(false)
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

// 监听priceInput变化，同步到product.price
watch(priceInput, (newVal) => {
  if (newVal === '') {
    product.price = 0
  } else {
    product.price = parseFloat(newVal)
  }
})

// 格式化价格输入
const formatPrice = () => {
  let value = priceInput.value.trim()
  
  // 1. 首先允许输入小数点，但确保只能有一个
  value = value.replace(/[^0-9.]/g, '')
  
  // 限制只能有一个小数点
  const decimalCount = (value.match(/\./g) || []).length
  if (decimalCount > 1) {
    const firstDotIndex = value.indexOf('.')
    value = value.substring(0, firstDotIndex + 1) + value.substring(firstDotIndex + 1).replace(/\./g, '')
  }
  
  // 2. 处理小数点后的位数
  const parts = value.split('.')
  if (parts.length > 1) {
    if (parts[1].length > 2) {
      parts[1] = parts[1].substring(0, 2)
    }
    
    if (parts[1].length === 0) {
      value = parts[0] + '.'
    } else {
      value = parts.join('.')
    }
  }
  
  // 3. 添加前导零
  if (value.startsWith('.')) {
    value = '0' + value
  }
  
  // 4. 限制最大长度（包括小数点）
  if (value.length > 10) {
    value = value.substring(0, 10)
  }
  
  // 5. 最终检查：如果用户删除了所有内容，清空输入
  if (value === '0') {
    value = ''
  }
  
  priceInput.value = value
}

// 处理API返回的分类数据
const processCategories = (categories) => {
  return categories
    .filter(cat => cat.children && cat.children.length > 0) // 只保留有子分类的项
    .map(root => ({
      value: root.id,
      label: root.display_name,
      children: root.children.map(child => ({
        value: child.id,
        label: child.display_name,
      }))
    }))
}

// 获取分类数据并处理
const fetchAndProcessCategories = async () => {
  try {
    // 检查本地存储中是否有缓存的分类数据
    const cachedCategories = localStorage.getItem('cachedCategories')
    if (cachedCategories) {
      categoryOptions.value = JSON.parse(cachedCategories)
      return
    }

    
    const response = await apiClient.get('/api/products/categories/choices/',)
    
    if (response.data && Array.isArray(response.data)) {
      // 处理API返回的分类数据
      const processedCategories = processCategories(response.data)
      categoryOptions.value = processedCategories
      
      // 存储到本地，避免重复请求
      localStorage.setItem('cachedCategories', JSON.stringify(processedCategories))
    }
  } catch (error) {
    console.error('获取分类数据失败:', error)
    ElMessage.error('获取分类数据失败，请稍后重试')
  }
}

// 检查登录状态并获取分类数据
onMounted(async () => {
  const token = localStorage.getItem('access_token')
  if (!token) {
    ElMessageBox.confirm(
      '您尚未登录，无法发布商品。是否前往登录页面？',
      '提示',
      {
        confirmButtonText: '前往登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      window.location.href = '/login'
    }).catch(() => {})
    return
  }

  localStorage.removeItem('cachedCategories')
  await fetchAndProcessCategories()
})

// 处理文件变化
const handleFileChange = (uploadFile, fileList) => {
  product.fileList = fileList
}

// 图片上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  
  if (product.fileList.length >= 9) {
    ElMessage.warning('最多只能上传9张图片')
    return false
  }
  
  return true
}

// 图片预览
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url || file.response?.data?.url || ''
  dialogVisible.value = true
}

// 移除图片
const handleRemove = (file, fileList) => {
  product.fileList = fileList
}

// 处理超出数量限制
const handleExceed = (files, fileList) => {
  ElMessage.warning(`最多只能上传9张图片，当前已上传${fileList.length}张`)
}

// 提交表单 - 发布商品
const submitProduct = async () => {
  product.action = 'publish'
  await saveProduct()
}

// 保存为草稿
const saveAsDraft = async () => {
  product.action = ''
  await saveProduct()
}

// 保存商品（发布或草稿）
const saveProduct = async () => {
  try {
    isSubmitting.value = true
    await productForm.value.validate()

    const token = localStorage.getItem('access_token')
    if (!token) throw new Error('请先登录')

    const formData = new FormData()
    formData.append('name', product.name)
    formData.append('price', product.price.toString())
    formData.append('category', product.category[1]) // 使用二级分类ID
    formData.append('description', product.description || '')
    formData.append('delivery_method', product.delivery_method)
    formData.append('delivery_location', product.delivery_location.join(' '))
    formData.append('action', product.action)
    
    // 添加图片
    product.fileList.forEach(file => {
      if (file.raw) formData.append('images', file.raw)
    })

    // 调用API
    await apiClient.post('/api/products/seller/', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })

    ElMessage.success(product.action === 'publish' ? '发布成功！' : '已保存为草稿！')
    setTimeout(() => window.location.href = '/Mine/fabu', 1500)
  } catch (error) {
    if (error !== 'cancel') {
      // 修改错误处理逻辑
      let errorMsg = '操作失败'
      if (error.response) {
        // 优先显示后端返回的具体错误信息
        errorMsg =error.response.data?.message || 
                  error.response.data?.error || 
                  error.message
      } else {
        errorMsg = error.message
      }
      ElMessage.error(`操作失败: ${errorMsg}`)
      
      if (error.response?.status === 401) {
        localStorage.removeItem('access_token')
        window.location.href = '/login'
      }
    }
  }  finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.publish-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  padding: 20px;
  background-color: #f5f7fa;
}

.publish-card {
  width: 100%;
  max-width: 800px;
  border-radius: 12px;
}

.card-header {
  text-align: center;
}

.card-header .title {
  margin: 0;
  color: var(--el-text-color-primary);
  font-size: 24px;
}

.image-uploader {
  width: 100%;
}

:deep(.el-upload-list__item) {
  transition: all 0.3s;
}

:deep(.el-upload-list__item:hover) {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.button-group {
  display: flex;
  gap: 12px;
}

.submit-btn {
  flex: 1;
  height: 48px;
  font-size: 16px;
  margin-top: 20px;
}

.draft-btn {
  flex: 1;
  height: 48px;
  font-size: 16px;
  margin-top: 20px;
}
</style>